package com.ls.hnks.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.ls.hnks.common.constant.AttachTypeConstant;
import com.ls.hnks.common.constant.FilePathConstant;
import com.ls.hnks.util.Result;
import com.ls.hnks.util.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SaCheckLogin
@RestController
@RequestMapping("/file")
@SuppressWarnings("all")
public class FileController {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Value("${file.staticAccessPath}")
    private String staticAccessPath;

    /**
     * 上传到本地目录
     *
     * @param request
     * @return
     */
    @PostMapping("/upload/avatar")
    public Result uploadAvatar(HttpServletRequest request) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        if (multipartFile == null || multipartFile.getOriginalFilename() == null) {
            return Result.error(ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }
        // 通过UUID生成新的文件名
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();
        String newFilename = uuid + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 放在自定义的外部目录
        String pathName = uploadFolder + FilePathConstant.AVATAR_IMAGE_SUB_PATH;
        File folder = new File(pathName);
        if (!folder.isDirectory() && !folder.mkdirs()) {
            throw new RuntimeException("文件夹创建失败");
        }

        try {
            multipartFile.transferTo(new File(folder, newFilename));
        } catch (IOException exception) {
            throw new RuntimeException(exception.getMessage());
        }

        String uriHeadPath =getUriHeadPath(staticAccessPath);
        String uriPath = uriHeadPath + FilePathConstant.AVATAR_IMAGE_SUB_PATH +"/"+ newFilename;
        return Result.ok(uriPath);
    }

    @PostMapping("/upload/attach")
    public Result uploadAttach(HttpServletRequest request,
                               @RequestParam(value = "attachType",required = true) String attachType) {

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");
        if (multipartFile == null || multipartFile.getOriginalFilename() == null) {
            return Result.error(ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }

        // 通过UUID生成新的文件名
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();
        String newFilename = uuid + originalFilename.substring(originalFilename.lastIndexOf("."));

        String pathName = "";
        String uriLastPath = "";
        if(AttachTypeConstant.IMAGE.equalsIgnoreCase(attachType)){
            pathName = uploadFolder + FilePathConstant.ATTACH_IMAGE_SUB_PATH;
            uriLastPath = FilePathConstant.ATTACH_IMAGE_SUB_PATH;
        }else if(AttachTypeConstant.DOCUMENT.equalsIgnoreCase(attachType)){
            pathName = uploadFolder + FilePathConstant.ATTACH_DOCUMENT_SUB_PATH;
            uriLastPath = FilePathConstant.ATTACH_DOCUMENT_SUB_PATH;
        }

        // 放在自定义的外部目录
        File folder = new File(pathName);
        if (!folder.isDirectory() && !folder.mkdirs()) {
            throw new RuntimeException("文件夹创建失败");
        }
        try {
            multipartFile.transferTo(new File(folder, newFilename));
        } catch (IOException exception) {
            throw new RuntimeException(exception.getMessage());
        }

        String uriHeadPath =getUriHeadPath(staticAccessPath);
        String uripath = uriHeadPath + uriLastPath +"/"+ newFilename;
        return Result.ok(uripath);
    }

    /**
     * 获取文件头部地址
     * @param staticAccessPath
     * @return
     */
    private String getUriHeadPath(String staticAccessPath){
        Pattern pattern = Pattern.compile("\\w+");
        Matcher matcher = pattern.matcher(staticAccessPath);
        String matchStr = "";
        if (matcher.find()) {
           matchStr = matcher.group();
        }
        return matchStr;
    }
}
